package com.atguigu.edu.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.edu.common.Constant;
import redis.clients.jedis.Jedis;

import java.sql.Connection;
import java.util.List;




public class DimUtil {
    
    public static JSONObject readDimFromPhoenix(Connection conn,
                                                String table,
                                                String id) throws Exception {
        
        String sql = "select * from " + table + " where id=?";
        Object[] args = new Object[]{id};
        List<JSONObject> list = JdbcUtil.queryList(conn, sql, args, JSONObject.class, false);
        return list.get(0);
    }
    
    
    public static JSONObject readDim(Jedis jedis, Connection phoenixConn, String table, String id) throws Exception {
        // 1. 先从 redis 读取维度数据
        JSONObject dim = readDimFromRedis(jedis, table, id);
        // 2. 如果读取到了,则直接返回结果
        if (dim == null) {
            System.out.println(table + " " + id + "查询的数据库");
            // 3. 如果没有读取到, 则去 phoenix 读取维度
            dim = readDimFromPhoenix(phoenixConn, table, id);
            // 4. 把读到的结果写入到缓存(redis)中
            writeToRedis(jedis, table, id, dim);
        }else{
            System.out.println(table + " " + id + "查询的 redis");
        }
        
        
        return dim;
    }
    
    // 把维度数据写入到 redis 中
    private static void writeToRedis(Jedis jedis, String table, String id, JSONObject dim) {
        String key = getKey(table, id);

        jedis.setex(key, Constant.TWO_DAY_SECONDS, dim.toJSONString());
    }
    
    public static String getKey(String table, String id) {
        return table + ":" + id;
    }
    
    // 从 redis 读取维度数据
    private static JSONObject readDimFromRedis(Jedis jedis, String table, String id) {
        String json = jedis.get(getKey(table, id));
    
        if (json != null) {
            return JSON.parseObject(json);
        }
        return null;
    }
}
